package com.lunevich.json.helpers;

import java.io.StringReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.Context;

import com.lunevich.json.handler.ApplicationXMLHandler;

public class XMLManager {
	
	private Context context;
	
	public XMLManager(Context context) {
		this.context = context;
	}
	
	public ApplicationXMLHandler getApplicationXMLHandler(String url) throws Exception {
		
		/* Create a URL we want to load some xml-data from. */
		String response = HttpManager.getHttpManager(context).getXMLDataFromUrl(url, context);
		
		/* Get a SAXParser from the SAXPArserFactory. */
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		/* Get the XMLReader of the SAXParser we created. */
		XMLReader xr = sp.getXMLReader();
		
		/* Create a new ContentHandler and apply it to the XML-Reader */
		ApplicationXMLHandler applcationXMLHandler = new ApplicationXMLHandler();
		xr.setContentHandler(applcationXMLHandler);

		/* Parse the xml-data from our URL. */
		InputSource inputSource = new InputSource();
		inputSource.setEncoding("UTF-8");
		inputSource.setCharacterStream(new StringReader(response));

		/* Parse the xml-data from our URL. */
		xr.parse(inputSource);
		/* Parsing has finished. */
		
		return applcationXMLHandler;
	}	
}